package cat.joronya.supermanager.team;

import java.text.NumberFormat;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.drawer.EmptyMessageFragment;
import cat.joronya.supermanager.widget.CheckableRelativeLayout;

public class MyTeamsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>
{
	// pel Log
	private static final String TAG = "supermanager";
	
	// loader id
	private static final int LIST_LOADER = 0x01;
	
	// jornada que estem mostrant
	private int day = 0;
	private int nextDay = 0;
	
	// the adapter
	private MyTeamsAdapter adapter;
	
	final NumberFormat nf = NumberFormat.getInstance(new Locale("es", "es"));
	
	// projection tenint en compte la query al provider
	private String[] PROJECTION = new String[] {
            "tdDay."+Supermanager.MyTeam._ID, 					// 0
            "tdDay."+Supermanager.MyTeam.ID_EQU, 				// 1
            "tdDay."+Supermanager.MyTeam.NAME, 					// 2
            "tdDay."+Supermanager.MyTeam.DAY, 					// 3
            "tdDay."+Supermanager.MyTeam.POINTS,				// 4
            "tdDay."+Supermanager.MyTeam.GENERAL,				// 5
            "tdDay."+Supermanager.MyTeam.BROKER,				// 6
            "tdDay."+Supermanager.MyTeam.POINTS_CLASSIFICATION,	// 7
            "tdDay."+Supermanager.MyTeam.GENERAL_CLASSIFICATION,// 8
            "tdDay."+Supermanager.MyTeam.BROKER_CLASSIFICATION,	// 9
            "tdDay."+Supermanager.MyTeam.POINTS_BEST,			// 10
            "tdDay."+Supermanager.MyTeam.POINTS_AVERAGE,		// 11
            "tdDay."+Supermanager.MyTeam.BEST_CLASSIFICATION,	// 12
            "tdDay."+Supermanager.MyTeam.MODIFIED_DATE, 		// 13
            "tdNext."+Supermanager.MyTeam.STATUS,				// 14
            "tdNext."+Supermanager.MyTeam.TEAM_PLAYERS			// 15
    };
    
    boolean mDualPane;
    int mCurCheckPosition = 0;
    long mCurCheckId = 0;
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) 
	{
    	// If not container present, don't generate the view so this fragment
    	// is not visible. Doing so, may cause problems with FragmentManager on
    	// recreation of the activity when orientation changes occur and different
    	// layout is loaded with id's no present anymore on it.
    	if( container == null )
    	{
    		return null;
    	}
    	
    	View view = inflater.inflate(R.layout.my_teams_list, null);
    	
    	// If no data was given in the intent, then use our default content provider.
        Intent intent = getActivity().getIntent();
        Uri plUri = getActivity().getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.MyTeam.CONTENT_URI;
            intent.setData(Supermanager.MyTeam.CONTENT_URI);
        }
        
        // per si venim de canvi d'orientacio, agafem el id de l'equip a mostrar al inciar
        mCurCheckId = getActivity().getIntent().getLongExtra("cat.joronya.supermanager.myteams.idequ",0);
        mCurCheckPosition = getActivity().getIntent().getIntExtra("cat.joronya.supermanager.myteams.position", 0);
        
        // retrieve day and status
		Cursor duetimeCursor = getActivity().getContentResolver().query(Supermanager.Home.CONTENT_URI, 
				Supermanager.Home.PROJECTION,
				null, null, Supermanager.Home.DEFAULT_SORT_ORDER);
		if( duetimeCursor.moveToFirst() )
		{
			day = duetimeCursor.getInt(1);
			nextDay = duetimeCursor.getInt(5);
		}
		duetimeCursor.close();
		
		// Mostrem la jornada actual a la capçalera
		TextView dayTextVieww = (TextView) view.findViewById(R.id.my_teams_list_jornada);
		dayTextVieww.setText(getResources().getString(R.string.my_teams_list_jornada, Integer.valueOf(day).toString()));
	
        // Used to map notes entries from the database to views
        adapter = new MyTeamsAdapter(getActivity().getApplicationContext(), null);
        setListAdapter(adapter);
        
        // initialize the loader
        //getLoaderManager().initLoader(LIST_LOADER, null, this);
        
        return view;
	}
    
    @Override
	public void onViewCreated(View view, Bundle savedInstanceState) 
    {
		super.onViewCreated(view, savedInstanceState);
		
		 // Check to see if we have a frame in which to embed the details
        // fragment directly in the containing UI.
        View detailsFrame = getActivity().findViewById(R.id.detail_fragment);
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

        if(savedInstanceState != null) 
        {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
            mCurCheckId = savedInstanceState.getLong("curId", 0);
        }

        if(mDualPane) 
        {
            // In dual-pane mode, the list view highlights the selected item.
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition, mCurCheckId);
        }
	}
    
    @Override
    public void onResume() 
    {
    	// resetejem el loader per canviar recarregar si canvis al refresh team
        getLoaderManager().restartLoader(LIST_LOADER, null, this);
    	super.onResume();
    }

    /*@Override
    public void onConfigurationChanged(Configuration newConfig) 
    {
    	// resetejem el loader per canviar recarregar si canvis al refresh team
        getLoaderManager().restartLoader(LIST_LOADER, null, this);
        
    	super.onConfigurationChanged(newConfig);
    }*/
    
	@Override
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
        outState.putLong("curId", mCurCheckId);
    }
    
    /**
	 * Al clicar una lliga privada anem al detall.
	 */
    @Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		Log.d(TAG,"veient detall del meu equip amb _id: "+id);
		TextView textView = (TextView)v.findViewById(R.id.my_teams_list_row_id);
		long idequ = Long.valueOf(textView.getText().toString());
		showDetails(position,idequ);
	}
    
    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index, long id) 
    {
        mCurCheckPosition = index;
        mCurCheckId = id;

        if(mDualPane) 
        {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            Fragment empty = getFragmentManager().findFragmentById(R.id.detail_fragment);
            
            // not initialized and id == 0, set empty fragment
            if( empty == null && id == 0 )
            {
            	// show empty fragment with message
            	EmptyMessageFragment emptyMessageFragment = EmptyMessageFragment.newInstance(getString(R.string.my_teams_list_empty_fragment_message));
            	FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.detail_fragment, emptyMessageFragment);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
            // first selection, change empty message fragment with detail
            else if( empty instanceof EmptyMessageFragment )
            {
            	// Make new fragment to show this selection.
            	MyTeamDetailFragment detail = MyTeamDetailFragment.newInstance(id);
            	
            	// Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
               	FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.detail_fragment, detail);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
            // otherwise, change detail with other detail
            else
            {
            	MyTeamDetailFragment detail = (MyTeamDetailFragment)
                    getFragmentManager().findFragmentById(R.id.detail_fragment);
            	
            	if( detail == null )
            	{
            		detail = MyTeamDetailFragment.newInstance(id);

            		// Execute a transaction, replacing any existing fragment
            		// with this one inside the frame.
            		FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.detail_fragment, detail);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
            	}
            	else if( detail.getShownIndex() != id) 
            	{
            		// Make new fragment to show this selection.
            		detail = MyTeamDetailFragment.newInstance(id);

            		// Execute a transaction, replacing any existing fragment
            		// with this one inside the frame.
            		FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.detail_fragment, detail);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
            	}
            }
        } 
        else 
        {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), MyTeamDetailActivity.class);
            intent.putExtra("cat.joronya.supermanager.myteams.idequ", id);
            intent.putExtra("cat.joronya.supermanager.myteams.position", mCurCheckPosition);
            startActivity(intent);
        }
    }
    
    class MyTeamsAdapter extends CursorAdapter implements CheckableRelativeLayout.OnCheckedChangeListener
	{
    	public MyTeamsAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			// id_equ
			int idequ = cursor.getInt(1);
			TextView idequView = (TextView) view.findViewById(R.id.my_teams_list_row_id);
			idequView.setText(idequ+"");
			
			// name
			String name = cursor.getString(2);
			TextView nameView = (TextView) view.findViewById(R.id.my_teams_list_row_name);
			nameView.setText(name);
			
			// points
			float points = cursor.getFloat(4);
			TextView pointsView = (TextView) view.findViewById(R.id.my_teams_list_row_jornada);
			pointsView.setText(nf.format(points));

			// general
			float general = cursor.getFloat(5);
			TextView generalView = (TextView) view.findViewById(R.id.my_teams_list_row_general);
			generalView.setText(nf.format(general));

			// broker
			int broker = cursor.getInt(6);
			TextView brokerView = (TextView) view.findViewById(R.id.my_teams_list_row_broker);
			brokerView.setText(nf.format(broker));

			// classifications jornada
			int cJornada = cursor.getInt(7);
			TextView cJornadaView = (TextView) view.findViewById(R.id.my_teams_list_row_jornada2);
			cJornadaView.setText("("+nf.format(cJornada)+"º)");

			// classifications general
			int cGeneral = cursor.getInt(8);
			TextView cGeneralView = (TextView) view.findViewById(R.id.my_teams_list_row_general2);
			cGeneralView.setText("("+nf.format(cGeneral)+"º)");

			// classifications broker
			int cBroker = cursor.getInt(9);
			TextView cBrokerView = (TextView) view.findViewById(R.id.my_teams_list_row_broker2);
			cBrokerView.setText("("+nf.format(cBroker)+"º)");

			// status
			int status = cursor.getInt(14);
			ImageView statusView = (ImageView)view.findViewById(R.id.my_teams_list_row_status);
			switch(status)
			{
				case Supermanager.MyTeam.STATUS_LESIONAT:
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.lesio);
					break;
				case Supermanager.MyTeam.STATUS_DESCARTAT:
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.baixa);
					break;
				case Supermanager.MyTeam.STATUS_INCOMPLETE_TEAM:
					//aView.setVisibility(View.VISIBLE);
					//statusView.setImageResource(R.drawable.incomplet);
					statusView.setVisibility(View.GONE);
					break;
				case Supermanager.MyTeam.STATUS_NORMAL:
				default:
					statusView.setVisibility(View.INVISIBLE);
					break;
			}
			statusView.bringToFront();

			// team players
			String teamPlayers = cursor.getString(15);
			Log.d(TAG,"MyTeamsList status: "+status+", teamPlayers: "+teamPlayers);

			TextView teamPlayersView = (TextView) view.findViewById(R.id.my_teams_list_row_team_players);
			if( status == Supermanager.MyTeam.STATUS_INCOMPLETE_TEAM )
			{
				teamPlayersView.setText(getResources().getString(R.string.my_teams_list_row_team_players, teamPlayers));
				teamPlayersView.bringToFront();
				teamPlayersView.setVisibility(View.VISIBLE);
			}
			else
			{
				teamPlayersView.setVisibility(View.INVISIBLE);
			}
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			CheckableRelativeLayout row = (CheckableRelativeLayout)inflater.inflate(R.layout.my_teams_list_row, parent, false);
			row.setOnCheckedChangeListener(this);
			return row;
		}

		public void onCheckedChanged(CheckableRelativeLayout layout, boolean isChecked) 
		{
			layout.setBackgroundColor((isChecked)? 
					getResources().getColor(R.color.blue):getResources().getColor(R.color.white));
		}
    }
    
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) 
	{
		// preparem la URI del nou llistat al provider de my teams
		Uri uri = Uri.withAppendedPath(Supermanager.MyTeam.CONTENT_URI_LIST, day+"");
		uri = Uri.withAppendedPath(uri, nextDay+"");
		
		CursorLoader cursorLoader = new CursorLoader(getActivity(),
				uri, 
				PROJECTION, 
				null, 
				null, 
				Supermanager.MyTeam.DEFAULT_SORT_ORDER);
	    return cursorLoader;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
	{
		adapter.swapCursor(cursor);
	}

	public void onLoaderReset(Loader<Cursor> loader) 
	{
		adapter.swapCursor(null);
	}   
}
